//
//  ImageDescriptionDelegate.m
//  cTypica
//
//  Created by David Kavanagh on 10/21/08.
//  Copyright 2008 directThought. All rights reserved.
//

#import "ImageDescriptionDelegate.h"

@implementation ImageDescriptionDelegate
@synthesize imageReceiver;

+ (id)delegateWithReceiver:(id<ImageDescriptionProtocol>)receiver {
	ImageDescriptionDelegate *ret = [self alloc];
	ret.imageReceiver = receiver;
	return ret;
}

// XML parser delegate methods
- (void)parser: (NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	if ([elementName isEqualToString:@"imagesSet"]) {
		[imageReceiver startNewImageDescription];
		halting = NO;
	}
	else if (!inProductCodes && [elementName isEqualToString:@"item"]) {
		item = [ImageDescription alloc];
		inProductCodes = NO;
	}
	else if ([elementName isEqualToString:@"productCodes"]) {
		inProductCodes = YES;
		item.productCodes = [NSMutableSet setWithCapacity:1];
	}
}

- (void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	NSString *cleanString = [currentStringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[currentStringValue setString:@""];
	if ([elementName isEqualToString:@"imagesSet"]) {
		[imageReceiver endNewImageDescription];
	}
	else if (!inProductCodes && [elementName isEqualToString:@"item"]) {
		if (!halting && ![imageReceiver imageDescriptionReady:item]) {
			halting = YES;
			//if ([imageReceiver conformsToProtocol:@protocol(ImageDescriptionProtocol)]) {
			//	[imageReceiver endNewImageDescription];
			//}
			//[parser abortParsing];
		}
		//[item release];
		item = nil;
	}
	else if ([elementName isEqualToString:@"imageId"]) {
		item.imageId = cleanString;
	}
	else if ([elementName isEqualToString:@"imageLocation"]) {
		item.imageLocation = cleanString;
	}
	else if ([elementName isEqualToString:@"imageState"]) {
		item.imageState = cleanString;
	}
	else if ([elementName isEqualToString:@"imageOwnerId"]) {
		item.imageOwnerId = cleanString;
	}
	else if ([elementName isEqualToString:@"isPublic"]) {
		item.isPublic = [cleanString isEqualToString:@"true"];
	}
	else if ([elementName isEqualToString:@"productCodes"]) {
		inProductCodes = NO;
	}
	else if ([elementName isEqualToString:@"productCodes"]) {
		[item.productCodes addObject:cleanString];
	}
	else if ([elementName isEqualToString:@"architecture"]) {
		item.architecture = cleanString;
	}
	else if ([elementName isEqualToString:@"imageType"]) {
		item.imageType = cleanString;
	}
	else if ([elementName isEqualToString:@"kernelId"]) {
		item.kernelId = cleanString;
	}
	else if ([elementName isEqualToString:@"ramdiskId"]) {
		item.ramdiskId = cleanString;
	}
	//[cleanString release];
}

@end
